<template>
  <div class="ai">
    <div class="box">
      <div class="ai-header">
        AI助手
      </div>
      <div class="ai-content" ref="contentRef">
        <div v-for="(item, index) in chatArr" :key="`${item.id}-${index}`" class="box2">
          <div v-if="item.userText" class="main right">
            <div class="text">
              {{ item.userText }}
            </div>
            <div class="img">
              <img :src="img" alt="user">
            </div>
          </div>
          <div v-if="item.aiText" class="main left">
            <div class="img">
              <img src="../static/imgs/images/AiChat.png" alt="AI">
            </div>
            <div class="text">
              <vue3-markdown-it class="markdown" :source="item.aiText" />
            </div>
          </div>

        </div>

      </div>
      <div class="ai-footer d-flex align-items-center justify-content-between ">
        <div class="textarea ">
          <textarea @keyup.enter="getAiChatFn" v-model="text" placeholder="请输入内容"></textarea>
        </div>
        <div class="send">
          <button @click="getAiChatFn" class="btn btn-outline-warning">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>
<!-- 非流式AI回答 -->
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter"
import { imgUrl, getAiChat } from "@/api/index";
import { ref } from "vue";
import { Toast } from "vant";
const counter = useCounterStore();
const img = imgUrl((counter.userData.imgUrl));
import Vue3MarkdownIt from 'vue3-markdown-it';
import { ElMessage } from "element-plus";

const text = ref<string>('');
interface aiItem {
  aiText: string;
  id: string | number;
  userText?: string;
}
const chatArr = ref<aiItem[]>([
  {
    aiText: '你好呀，我是你的AI助手，请问有什么可以帮你？',
    id: '5904936619099315'
  }
]);
const historyArr = JSON.parse(localStorage.getItem('chatArr') as string)
// console.log(historyArr);
if (historyArr && historyArr.length > 0) {
  chatArr.value = historyArr;
}
// 添加ref引用
const contentRef = ref<HTMLDivElement | null>(null);
// 滚动到最底部
const scrollToBottom = () => {
  if (contentRef.value) {
    contentRef.value.scrollTop = contentRef.value.scrollHeight;
  }
};
// 获取AI回复
const getAiChatFn = async () => {
  // 检查登录状态
  const token = localStorage.getItem('TTOO');
  if (token) {
    // 登录状态
    const userStatus = await counter.loginedStatusFn(token)
    // console.log(userStatus)
    if (userStatus) {
      // console.log(text.value);
      if (text.value.trim() == '') {
        ElMessage({
          showClose: true,
          message: '你还没写呢~~',
          type: 'warning',
          offset: 100,
          plain: true,
        })
        return false
      } else {
        chatArr.value.push({
          userText: text.value,
          aiText: '',
          id: new Date().getTime()
        })
      }
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: 'AI正在思考...'
      })
      await getAiChat({ text: text.value })
        .then(
          res => {
            if (res.data.code === 200) {
              // AI回复的内容文本
              const response = res.data.result.choices[0].message.content;
              const id = res.data.result.id
              // console.log(res.data);
              chatArr.value.map(item => {
                if (item.userText == text.value) {
                  item.aiText = response;
                  item.id = id;
                }
              })
              // console.log(chatArr.value);
              localStorage.setItem('chatArr', JSON.stringify(chatArr.value));
              // chatArr.value = newArr;
              text.value = '';
            }
          },
          err => {
            console.log(err);
          }
        ).finally(() => {
          Toast.clear();
          scrollToBottom()
        })
    } else {
      ElMessage({
        showClose: true,
        message: '你登录状态已失效，请重新登录~~',
        type: 'error',
        offset: 100,
        plain: true,
      })
    }
  } else {
    // 未登录状态
    ElMessage({
      showClose: true,
      message: '你还没登录呢~~',
      type: 'error',
      offset: 100,
      plain: true,
    })
  }
}

</script>

<style lang="less" scoped>
@keyframes show {
  0% {
    opacity: 0.65;
    transform: translateY(-3%);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}


&::v-deep pre {
  padding: 10px;
  border-radius: 5px;
  background-color: rgba(10, 10, 10, 0.9) !important;
  color: #fff !important;
}

.ai {
  width: 100%;
  height: 100%;
  background-image: url(../static/imgs/images/aiBg.jpg);
  background-size: cover;
  background-position: center;
  position: relative;
  animation: show 1s ease-in-out;



  .box {
    width: 550px;
    height: 530px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(255, 255, 255, .9);
    margin: 0 auto;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    border-radius: 15px !important;

    .ai-header {
      width: 100%;
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 28px;
      font-weight: bold;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.5);
      border-top-left-radius: 15px;
      border-top-right-radius: 15px;
    }

    .ai-content {
      width: 100%;
      overflow-y: scroll;
      height: 425px;
      padding: 5px 0 10px;

      .box2 {
        width: 100%;
        display: flex;
        flex-direction: column;

        .main {
          max-width: 90%;
          padding: 10px;
          border-radius: 10px;
          display: flex;
          align-items: flex-start;

          &.left {
            align-self: flex-start;

            .text {
              width: calc(100% - 50px);
              // margin-top: 7px;
              margin-left: 10px;
            }
          }

          &.right {
            align-self: flex-end;

            .text {
              background-color: #FFA500;
              margin-right: 10px;
            }
          }

          .img {
            flex-shrink: 0;
            width: 50px;
            height: 50px;

            img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }

          .text {
            margin-top: 8px;
            border-radius: 10px;
            padding: 5px 10px;
            background-color: #fff;
            font-size: 16px;
            color: #333;
          }
        }
      }

      &::-webkit-scrollbar {
        display: none;
      }



    }

    .ai-footer {
      padding: 5px;
      padding-left: 10px;
      height: calc(100% - 480px);

      .btn {
        width: 55px;
        padding: 5px;

      }

      .textarea {
        width: calc(100% - 65px);
        height: 100%;
        border-radius: 10px;
        padding-top: 5px;
        padding-left: 5px;
        border: 1px solid #ccc;

        textarea {
          background-color: transparent;
          resize: none;
          border: none;
          outline: none;
          width: 100%;
          height: 100%;

          &::-webkit-scrollbar {
            display: none;
          }
        }
      }
    }
  }
}

@media (max-width:580px) {
  .ai {
    >.box {
      width: 90%;
      // height: 100%;
      border-radius: 0;
    }
  }
}
</style>
